const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// 图表配置
const diagrams = {
  // 系统架构类
  'system-architecture': {
    type: 'graph',
    title: 'HRC平台整体系统架构',
    category: 'architecture'
  },
  'architecture': {
    type: 'graph', 
    title: 'HRC平台技术架构总览',
    category: 'architecture'
  },
  'deployment-architecture': {
    type: 'graph',
    title: 'HRC平台部署架构',
    category: 'architecture'
  },
  'security-architecture': {
    type: 'graph',
    title: 'HRC平台安全架构',
    category: 'architecture'
  },
  'data-flow-architecture': {
    type: 'graph',
    title: 'HRC平台数据流架构',
    category: 'architecture'
  },
  // 业务流程类
  'business-process': {
    type: 'flowchart',
    title: 'HRC平台核心业务流程',
    category: 'process'
  },
  'user-registration-flow': {
    type: 'flowchart',
    title: 'HRC平台用户注册流程',
    category: 'process'
  },
  'asset-trading-flow': {
    type: 'flowchart',
    title: 'HRC平台资产交易流程',
    category: 'process'
  },
  'user-experience-flow': {
    type: 'flowchart',
    title: 'HRC平台用户体验流程',
    category: 'process'
  },
  // 专项技术类
  'blockchain-integration': {
    type: 'graph',
    title: 'HRC平台区块链集成架构',
    category: 'technical'
  },
  'ai-valuation-workflow': {
    type: 'flowchart',
    title: 'HRC平台AI价值评估工作流程',
    category: 'technical'
  }
};

// 生成单个图表
function generateDiagram(name, config) {
  const mmdFile = path.join('temp', `${name}.mmd`);
  const svgFile = path.join('docs', 'assets', 'diagrams', `${name}.svg`);
  
  try {
    // 确保临时目录存在
    if (!fs.existsSync('temp')) {
      fs.mkdirSync('temp');
    }
    
    // 确保输出目录存在
    const outputDir = path.dirname(svgFile);
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }
    
    console.log(`生成图表: ${name}`);
    
    // 使用Mermaid CLI生成SVG
    const command = `npx @mermaid-js/mermaid-cli -i "${mmdFile}" -o "${svgFile}" -c mermaid-config.json`;
    execSync(command, { stdio: 'inherit' });
    
    console.log(`✅ 成功生成: ${svgFile}`);
    return true;
  } catch (error) {
    console.error(`❌ 生成失败: ${name}`, error.message);
    return false;
  }
}

// 生成所有图表
function generateAllDiagrams() {
  console.log('开始生成HRC项目架构图和流程图...');
  
  let successCount = 0;
  let totalCount = Object.keys(diagrams).length;
  
  for (const [name, config] of Object.entries(diagrams)) {
    if (generateDiagram(name, config)) {
      successCount++;
    }
  }
  
  console.log(`\n生成完成: ${successCount}/${totalCount} 个图表`);
  
  if (successCount === totalCount) {
    console.log('🎉 所有图表生成成功!');
  } else {
    console.log('⚠️  部分图表生成失败，请检查错误信息');
  }
}

// 清理临时文件
function cleanup() {
  if (fs.existsSync('temp')) {
    fs.rmSync('temp', { recursive: true, force: true });
  }
}

// 主函数
function main() {
  try {
    generateAllDiagrams();
  } finally {
    cleanup();
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}

module.exports = {
  diagrams,
  generateDiagram,
  generateAllDiagrams
};